package com.manong.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 李茂鑫
 * @Date 2025/1/8 11:59
 * @Descripition
 */
@Data
@ConfigurationProperties(prefix = "jwt")
//jwt: JSON Web Token  prefix = "jwt" 表示配置文件中的属性需要以 jwt 为前缀。
@Component
public class JwtUtils {
    private String secret;
    //存储Jwt密钥
    private Long expiration;
    //JWT过期时间

    /**
     * 从数据中声明生成令牌
     * @param claims
     * @return
     */
    private String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration * 1000); //JWT的过期时间
        return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact();
        //.setClaims(claims)设置声明
        //.setExpiration(expirationDate)设置过期时间
        //.signWith(SignatureAlgorithm.ES512, secret)使用签名算法和密钥签名
        //.compact()生成JWT字符串
    }

    /**
     * 从令牌中获取声明数据
     * @param token
     * @return
     */

    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            //.parser()解析JWT，利用secret密钥验证JWT的签名，并获取声明
            //setSigningKey是设置密钥，getBody是获取负载信息
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    /**
     * 生成令牌（根据 UserDetails生成 JWT。）
     * @param userDetails
     * @return
     */

    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put(Claims.SUBJECT, userDetails.getUsername());
        //获取令牌用户名
        claims.put(Claims.ISSUED_AT, new Date());
        //获取当前时间
        return generateToken(claims);
    }

    /**
     * 从令牌中获取数据
     * @param token
     * @return
     */

    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 判断令牌是否过期
     * @param token
     * @return
     */
    public Boolean isTokenExpired(String token) {
        Claims claims = getClaimsFromToken(token);
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 刷新token
     * @param token
     * @return
     */

    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put(Claims.ISSUED_AT, new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 验证token
     * @param token
     * @param userDetails
     * @return
     */
    public Boolean ValidateToken(String token, UserDetails userDetails) {
        User user = (User) userDetails;
        String username = getUserNameFromToken(token);
        return (username.equals(user.getUsername()) && !isTokenExpired(token));
    }
}
